#include "browser.h"
#include "fenetreconnexion.h"
#include "arbrebdd.h"
#include "historiquerequetes.h"

Browser::Browser(QWidget *parent) : QMainWindow(parent)
{
    setupUi();

    if (QSqlDatabase::drivers().isEmpty())
    {
        QMessageBox::information(this, "Aucun drivers de base de données trouvés", "Veuillez vous renseigner auprès de la documentation de Qt pour savoir comment construire les plugins");
    }

    emit statusMessage("Prêt.");
}

void Browser::setupUi()
{
    setWindowTitle("Inc++");

    // Création de la barre de status
    statusB = new QStatusBar;
    statusB->setStyleSheet("color: rgb(255,0,0); font: 18px bold;");
    setStatusBar(statusB);

    // Création du menu
    fileMenu = menuBar()->addMenu("Fichier");
    fileMenu->addAction("Ajouter Connexion...", this, SLOT(addConnection()));
    fileMenu->addSeparator();
    fileMenu->addAction("Quitter", qApp, SLOT(quit()));

    splitterDb = new QSplitter;
    splitterDb->setOrientation(Qt::Horizontal);

    splitterRequete = new QSplitter;
    splitterRequete->setOrientation(Qt::Horizontal);

    connectionWidget = new ArbreBdd;
    historique = new HistoriqueRequetes;

    table = new QTableView;
    table->setContextMenuPolicy(Qt::ActionsContextMenu);
    table->setSelectionBehavior(QAbstractItemView::SelectRows);

    QHBoxLayout* hbTable = new QHBoxLayout;
    hbTable->addWidget(table);
    QGroupBox* gbTable = new QGroupBox("Résultat");
    gbTable->setLayout(hbTable);
    gbTable->setStyleSheet("QGroupBox { background-color : rgb(170,170,170); }");

    sqlEdit = new QTextEdit;
    clearButton = new QPushButton("Nettoyer");
    submitButton = new QPushButton("Envoyer");

    splitterDb->addWidget(connectionWidget);
    splitterDb->addWidget(gbTable);
    splitterDb->setStretchFactor(1,3);

    hbButton = new QHBoxLayout;
    hbButton->addWidget(clearButton);
    hbButton->addWidget(submitButton);

    splitterRequete->addWidget(sqlEdit);
    splitterRequete->addWidget(historique);
    splitterRequete->setStretchFactor(0,3);

    vbGroup = new QVBoxLayout;
    vbGroup->addWidget(splitterRequete);
    vbGroup->addLayout(hbButton);
    groupBox = new QGroupBox("Requêtes SQL");
    groupBox->setLayout(vbGroup);

    splitterPrincipal = new QSplitter;
    splitterPrincipal->setOrientation(Qt::Vertical);
    splitterPrincipal->addWidget(splitterDb);
    splitterPrincipal->addWidget(groupBox);
    splitterPrincipal->setContentsMargins(10,10,10,10);
    splitterPrincipal->setStretchFactor(0,2);
    setCentralWidget(splitterPrincipal);

    QObject::connect(historique, SIGNAL(sendRequete(QString)), sqlEdit, SLOT(setText(QString)));
    QObject::connect(this, SIGNAL(statusMessage(QString)), statusBar(), SLOT(showMessage(QString)));
    QObject::connect(clearButton, SIGNAL(clicked()), this, SLOT(on_clearButton_clicked()));
    QObject::connect(submitButton, SIGNAL(clicked()), this, SLOT(on_submitButton_clicked()));
}

void Browser::exec()
{
    QString req = sqlEdit->toPlainText();
    QSqlQueryModel *model = new QSqlQueryModel(table);
    model->setQuery(QSqlQuery(req, connectionWidget->currentDatabase()));
    table->setModel(model);

    if (model->lastError().type() != QSqlError::NoError)
    {
        emit statusMessage(model->lastError().text());
    }
    else if (model->query().isSelect())
    {
        emit statusMessage("Requête OK.");
        historique->requeteListener(req);
    }
    else
    {
        emit statusMessage("Requête OK, nombre de lignes affectées : " + QString::number(model->query().numRowsAffected()));
        historique->requeteListener(req);
    }
}

QSqlError Browser::addConnection(QString driver, QString dbName, QString host, QString user, QString passwd, int port)
{
    int cCount = 0;

    QSqlError err;
    QSqlDatabase db = QSqlDatabase::addDatabase(driver, QString("Browser%1").arg(++cCount));
    db.setDatabaseName(dbName);
    db.setHostName(host);
    db.setPort(port);
    if (!db.open(user, passwd))
    {
        err = db.lastError();
        db = QSqlDatabase();
        QSqlDatabase::removeDatabase(QString("Browser%1").arg(cCount));
    }
    connectionWidget->refresh();

    return err;
}

void Browser::addConnection()
{
    FenetreConnexion fenetre(this);

    // Si le retour est la valeur "Accepted"
    if (fenetre.exec() == QDialog::Accepted)
    {
        // Si la checkbox de base de données prédéfinie est cochée
        if (fenetre.utiliseDBPredefinie())
        {
            QSqlDatabase::database("db_predefinie", false).close();
            QSqlDatabase::removeDatabase("db_predefinie");
            QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "db_predefinie");
            db.setDatabaseName(":memory:");
            if (!db.open())
            {
                QMessageBox::warning(this, "Impossible d'ouvrir la base de données", "Une erreur s'est produite lors de la connexion: " + db.lastError().text());
            }

            QSqlQuery q("", db);/*
            q.exec("drop table Movies");
            q.exec("drop table Names");
            q.exec("create table Movies (id integer primary key, Title varchar, Director varchar, Rating number)");
            q.exec("insert into Movies values (0, 'Metropolis', 'Fritz Lang', '8.4')");
            q.exec("insert into Movies values (1, 'Nosferatu, eine Symphonie des Grauens', 'F.W. Murnau', '8.1')");
            q.exec("insert into Movies values (2, 'Bis ans Ende der Welt', 'Wim Wenders', '6.5')");
            q.exec("insert into Movies values (3, 'Hardware', 'Richard Stanley', '5.2')");
            q.exec("insert into Movies values (4, 'Mitchell', 'Andrew V. McLaglen', '2.1')");
            q.exec("create table Names (id integer primary key, Firstname varchar, Lastname varchar, City varchar)");
            q.exec("insert into Names values (0, 'Sala', 'Palmer', 'Morristown')");
            q.exec("insert into Names values (1, 'Christopher', 'Walker', 'Morristown')");
            q.exec("insert into Names values (2, 'Donald', 'Duck', 'Andeby')");
            q.exec("insert into Names values (3, 'Buck', 'Rogers', 'Paris')");
            q.exec("insert into Names values (4, 'Sherlock', 'Holmes', 'London')");*/

            q.exec("create table test (title varchar, pond integer)");
            q.exec("insert into test values ('title1', 1)");
            q.exec("insert into test values ('title2', 2)");
            q.exec("insert into test values ('title3', 3)");
            q.exec("insert into test values ('title4', 4)");
            q.exec("insert into test values ('title5', 5)");
            q.exec("insert into test values ('title6', 6)");

            q.exec("create table num (nb integer)");
            q.exec("insert into num values (1)");
            q.exec("insert into num values (2)");
            q.exec("insert into num values (3)");
            q.exec("insert into num values (4)");
            q.exec("insert into num values (5)");
            q.exec("insert into num values (6)");

            connectionWidget->refresh();
        }
        else
        {
            QSqlError err = addConnection(fenetre.driverName(), fenetre.databaseName(), fenetre.hostName(), fenetre.userName(), fenetre.password(), fenetre.port());

            if(err.type() != QSqlError::NoError)
            {
                QMessageBox::warning(this, "Impossible d'ouvrir la base de données", "Une erreur s'est produite lors de la connexion: " + err.text());
            }
        }
    }
}
